import React from 'react';
import { Upload, message } from 'antd';
import { ossConfig } from '@/services/common';

export default class AliyunOSSUpload extends React.Component {
  state = {
    OSSData: {},
  }

  // 组件挂载完成后，进行初始化，获取OSS配置
  async componentDidMount() {
    await this.init();
  }

  // 初始化，获取OSS上传签名
  init = async () => {
    try {
      const OSSData = await ossConfig()
      this.setState({
        OSSData,
      });
    } catch (error) {
      message.error(error);
    }
  }

  // 文件上传过程中，触发的回调函数，直到上传完成
  onChange = ({ file }) => {
    console.log('Aliyun OSS:', file);
    if(file.status === 'done') {
      // 上传成功之后，把文件的key，设置为 某个表单项的值【***】
      if(this.props.setCoverKey) this.props.setCoverKey(file.key)
      // 上传完成后，若需要url，返回url给父组件
      if(this.props.insertImage) this.props.insertImage(file.url)
      message.success('上传成功!')
    }
  }

  // 获取额外的上传参数
  getExtraData = file => {
    const { OSSData } = this.state;
    return {
      key: file.key,
      OSSAccessKeyId: OSSData.accessid,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    }
  }

  // 选择文件之后，上传文件之前，执行的回调
  beforeUpload = async file => {
    const { OSSData } = this.state
    const expire = OSSData.expire * 1000
    // 如果签名过期了，重新获取
    if (expire < Date.now()) {
      await this.init()
    }
    // 自定义上传到某个目录
    const dir = 'react/'
    const suffix = file.name.slice(file.name.lastIndexOf('.'))
    const filename = Date.now() + suffix
    // 存放目录 + 文件名
    file.key = OSSData.dir + dir + filename
    file.url = OSSData.host + file.key
    return file
  }


  render() {
    const { value, accept, showUploadList } = this.props;
    const props = {
      accept: accept || '',
      name: 'file',
      fileList: value,
      action: this.state.OSSData.host,
      onChange: this.onChange,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
      listType: 'picture',
      maxCount: 1,
      showUploadList
    }
    return (
      <Upload {...props}>
        {this.props.children}
      </Upload>
    )
  }

  
}




